import React ,{Component}from 'react'
import { Provider } from 'react-redux'
import configureStore from './store'
import Root from './containers/root'
import { NavigationActions } from 'react-navigation'
import {
  BackHandler,
  ToastAndroid
} from 'react-native'

let store = configureStore();

class Main extends Component{
  render(){
    return (
        <Provider store={store}>
          <Root/>
        </Provider>
      )
    }
    componentWillMount(){  
      BackHandler.addEventListener('hardwareBackPress', this._onBackAndroid );  
    }  
      
      
    componentUnWillMount(){  
        BackHandler.addEventListener('hardwareBackPress', this._onBackAndroid);  
    }  
      
    _onBackAndroid=()=>{  
        let now = new Date().getTime();  
        if(now - lastBackPressed < 2500) {  
            return false;  
        }  
        lastBackPressed = now;  
        ToastAndroid.show('再点击一次退出应用',ToastAndroid.SHORT);  
        return true;  
    }  
  }
  export default Main;

const lastBackPressed = undefined;
/** 
 * 处理安卓返回键 
 */  
const defaultStateAction = Root.router.getStateForAction;  
Root.router.getStateForAction = (action,state) => {  
    if (
        state &&
        action.type === NavigationActions.BACK &&
        state.routes[state.index].params &&
        state.routes[state.index].params.isEditing
      ) {
        // Returning null from getStateForAction means that the action
        // has been handled/blocked, but there is not a new state
        return null;
      }

    if(state &&  state.routes.length === 1 && action.type === NavigationActions.BACK) {  
        if (lastBackPressed + 2000 < Date.now()) {  
            ToastAndroid.show("再点击一次退出应用",ToastAndroid.SHORT);  
            lastBackPressed = Date.now();  
            const routes = [...state.routes];  
            return {  
                ...state,  
                ...state.routes,  
                index: routes.length - 1,  
            };  
        }  
    }  
    return defaultStateAction(action,state);  
};  